﻿using Confluent.Kafka;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DataService.Helper.Kafka
{
    /// <summary>
    /// Kafka消息消费者
    /// </summary>
    public sealed class KafkaConsumer : KafkaBase
    {
        static LogHelper logHelper = new LogHelper();
        [Obsolete]
        public static string Consumer(string topic, string server, string groupId)
        {
            string data = string.Empty;
            var conf = new ConsumerConfig
            {
                GroupId = groupId,
                BootstrapServers = server,
                // Note: The AutoOffsetReset property determines the start offset in the event
                // there are not yet any committed offsets for the consumer group for the
                // topic/partitions of interest. By default, offsets are committed
                // automatically, so in this example, consumption will only start from the
                // earliest message in the topic 'my-topic' the first time you run the program.
                AutoOffsetReset = AutoOffsetReset.Earliest,
                EnableAutoCommit = true, //允许自动提交，默认间隔时间是1分钟
            };

            using (var c = new ConsumerBuilder<Ignore, string>(conf).Build())
            {
                c.Subscribe(topic);

                CancellationTokenSource cts = new CancellationTokenSource();
                Console.CancelKeyPress += (_, e) =>
                {
                    e.Cancel = true; // prevent the process from terminating.
                    cts.Cancel();
                };

                try
                {
                    while (true)
                    {
                        try
                        {
                            var cr = c.Consume(cts.Token);
                            data = cr.Value;
                            logHelper.Debug($"Consumed message '{data}' at: '{cr.TopicPartitionOffset}'.");
                        }
                        catch (ConsumeException e)
                        {
                            logHelper.Info($"Error occured: {e.Error.Reason}");
                        }
                    }
                }
                catch (OperationCanceledException ex)
                {
                    logHelper.Error(ex.Message);
                }
                c.Commit();
                // Ensure the consumer leaves the group cleanly and final offsets are committed.
                c.Close();
            }
            return data;
        }
    }
}
